package com.cdshangpai.photoapp.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSONObject;
import com.cdshangpai.photoapp.LogConfig;
import com.cdshangpai.photoapp.PhotoAppBaseActivity;
import com.cdshangpai.photoapp.R;
import com.cdshangpai.photoapp.databinding.ActivityLoveBinding;
import com.cdshangpai.photoapp.ui.caseui.CaseDetailActivity;
import com.cdshangpai.photoapp.ui.hotal.HotalDetailActivity;
import com.cdshangpai.photoapp.ui.main.LoginFragment;
import com.cdshangpai.utils.db.CaseDb;
import com.cdshangpai.utils.db.FormDb;
import com.cdshangpai.utils.db.HotalDb;
import com.cdshangpai.utils.db.beans.Account;
import com.cdshangpai.utils.db.beans.Case;
import com.cdshangpai.utils.db.beans.Form;
import com.cdshangpai.utils.db.beans.Hotal;
import com.cdshangpai.utils.offlinecache.FormSubmit;
import com.cdshangpai.utils.system.ScreenParams;
import com.google.android.flexbox.FlexboxLayoutManager;

import java.util.ArrayList;
import java.util.List;

public class LoveActivity extends PhotoAppBaseActivity {
    private static String s_name = "";
    private static String s_content = "";
    private static String s_phone = "";
    ActivityLoveBinding binding;
    CaseDb caseDb;
    HotalDb hotalDb;
    FormDb formDb;

    List<Case> cases = new ArrayList<>();
    List<Hotal> hotals = new ArrayList<>();

    public LoveActivity() {
        hotalDb = new HotalDb();
        caseDb = new CaseDb();
        formDb = new FormDb();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_love);
        binding.loveList.setOverScrollMode(View.OVER_SCROLL_NEVER);

        binding.setShowWarning(false);

//        adjustListWidth();

        initView();
        loadData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        binding.loveFormName.setText(s_name);
        binding.loveFormPhone.setText(s_phone);
        binding.loveFormContent.setText(s_content);
    }

    @Override
    protected void onPause() {
        super.onPause();
        s_name=binding.loveFormName.getText().toString();
        s_phone=binding.loveFormPhone.getText().toString();
        s_content=binding.loveFormContent.getText().toString();
    }

    /**
     * 调整图片列表宽度，固定显示3列
     */
    private void adjustListWidth() {
        Integer width = (ScreenParams.iconWidth + ScreenParams.colmargin * 2) * 3;
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) binding.loveListBody.getLayoutParams();
        lp.width = width;
        binding.loveListBody.setLayoutParams(lp);
    }

    /**
     * 初始化视图
     */
    private void initView() {
        LoveImageListAdapter loveImageListAdapter = new LoveImageListAdapter(this, null);
        binding.setAdapter(loveImageListAdapter);
        binding.setView(this);


        //点击后跳转详细页面
        loveImageListAdapter.onListViewClickListener=new OnListViewClickListener() {
            @Override
            public void onClick(Integer position) {
                List temp=binding.getAdapter().datas;
                LoveListItem item=binding.getAdapter().datas.get(position);

                Log.i(LogConfig.logTag,"loveitem=>"+JSONObject.toJSONString(item)+";position=>"+position);

                String param="";
                if(item.type.equals(LoveListItem.TYPE_CASE))
                {
                    Case cas=caseDb.queryById(item.id);
                    param= JSONObject.toJSONString(cas);
                    Intent intent=new Intent(getApplicationContext(),CaseDetailActivity.class);
                    intent.putExtra("param",param);
                    startActivity(intent);
                }
                else
                {
                    Hotal hotal=hotalDb.queryById(item.id);
                    param=JSONObject.toJSONString(hotal);
                    Log.i(LogConfig.logTag,param);
                    Intent intent=new Intent(getApplicationContext(),HotalDetailActivity.class);
                    intent.putExtra("param",param);
                    startActivity(intent);
                }
            }
        };

        FlexboxLayoutManager flexboxLayoutManager = FlexLayout.getFlexboxLayoutManager(this, false);
        binding.loveList.setLayoutManager(flexboxLayoutManager);

        binding.setNonedata(false);
    }

    /**
     * 加载数据
     */
    private void loadData() {
        new Thread() {
            @Override
            public void run() {
                List<Integer> ids = CaseDetailActivity.getSelectedCaseIds();
                cases = caseDb.queryByIds(ids);
                List<LoveListItem> datas = new ArrayList<>();
                for (Case cas : cases) {
                    LoveListItem item = new LoveListItem();
                    item.id = cas.id;
                    item.titleimg = cas.titleimg;
                    item.name = cas.title;
                    item.type = LoveListItem.TYPE_CASE;
                    datas.add(item);
                }

                /*LoveListItem temp=new LoveListItem();
                temp.id=35;
                temp.titleimg="content://media/external/downloads/1240";
                temp.name="nima";
                temp.type=LoveListItem.TYPE_CASE;
                datas.add(temp);
                datas.addAll(datas);
                datas.addAll(datas);
                datas.addAll(datas);
                datas.addAll(datas);*/

                hotals = hotalDb.queryByIds(HotalDetailActivity.getSelectedIds());
                for (Hotal hotal : hotals) {

                    Log.i(LogConfig.logTag,"查询酒店=>"+JSONObject.toJSONString(hotal));

                    LoveListItem item = new LoveListItem();
                    item.id = hotal.id;
                    item.titleimg = hotal.titleimg;
                    item.name = hotal.name;
                    item.type = LoveListItem.TYPE_HOTAL;
                    datas.add(item);
                }

                binding.getAdapter().datas = datas;
                LoveActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        binding.getAdapter().notifyDataSetChanged();
                        binding.setNonedata(binding.getAdapter().datas.size() == 0);
                    }
                });
            }
        }.start();
    }

    String name;
    String phone;
    String content;

    /**
     * 提交表单
     */
    public void onSubmit() {
         name = binding.loveFormName.getText().toString();
         phone = binding.loveFormPhone.getText().toString();
         content = binding.loveFormContent.getText().toString();
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(phone)) {
            binding.loveFormErrormsg.setText("姓名和电话号码必须填写");
            return;
        } else {
            binding.loveFormErrormsg.setText("");
        }

        binding.setShowWarning(true);
    }

    public void cancelSubmit(){
        binding.setShowWarning(false);
    }

    public void sureSubmit(){
        cancelSubmit();
        doSubmit(name,phone,content);
    }

    private void doSubmit(String name,String phone,String content){
        //异步线程执行提交
        new Thread(new Runnable() {
            @Override
            public void run() {
                Account account = LoginFragment.pickCacheAccount();
                List<Integer> ids = new ArrayList<>();
                for (Case cas : cases) {
                    ids.add(cas.id);
                }

                List<Integer> hotalids = new ArrayList<>();
                for (Hotal hotal : hotals) {
                    hotalids.add(hotal.getId());
                }
                Form form = new Form();
                form.name = name;
                form.phone = phone;
                form.remark = content;
                form.accountid = account.id;
                form.caseids = TextUtils.join(",", ids);
                form.videoids = TextUtils.join(",", hotalids);
                formDb.insert(form);

                new FormSubmit().notifySubmit();

                //完成提交，清除记录数据
                CaseDetailActivity.clearSelected();
                HotalDetailActivity.cleanSelected();

                LoveActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        binding.loveFormName.setText("");
                        binding.loveFormPhone.setText("");
                        binding.loveFormContent.setText("");
                    }
                });

                cleanContent();

                //提交完成后，自动返回主页
                LoveActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LoveActivity.this.finish();
                    }
                });
            }
        }).start();
    }

    public void gotoHome() {
        this.finish();
    }

    //清除表单内容
    public static void cleanContent() {
        s_name = "";
        s_content = "";
        s_phone = "";
    }


}